﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using Umi.Crypto.Abstraction.Keys;
using Umi.Web.Metadatas.Attributes;

namespace Umi.Web.Crypto.Crypto.Aes
{
    [Service("aesKeyCreator", Scoped = ServiceScoped.Single)]
    public class AesKeyCreator : IKeyParameterCreator
    {
        public KeyParameter Create(string key)
        {
            if (key == null)
                throw new ArgumentNullException(nameof(key));
            string[] keys = key.Split(',');
            byte[] keybit = Convert.FromBase64String(keys[0]);
            byte[] iv = keys.Length > 1 ? Convert.FromBase64String(keys[1]) : null;
            return new AesKeyParameter(keybit, iv);
        }

        public KeyParameter RandomKey()
        {
            RandomNumberGenerator rnd = RandomNumberGenerator.Create();
            byte[] key = new byte[16];
            byte[] iv = new byte[16];
            rnd.GetBytes(key);
            rnd.GetBytes(iv);
            return new AesKeyParameter(key, iv);
        }
    }

    public class AesKeyParameter : KeyParameter
    {
        public AesKeyParameter(byte[] key, byte[] iv)
        {
            Key = key;
            IV = iv;
        }

        public byte[] Key { get; }

        /// <summary>
        /// IV向量
        /// </summary>
        public byte[] IV { get; }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(Convert.ToBase64String(Key));
            if (IV == null)
                return sb.ToString();
            return sb.Append(",")
                .Append(Convert.ToBase64String(IV))
                .ToString();
        }
    }
}
